#include "stdafx.h"
#include "HttpClient.h"
#include "parser.h"


// static
void HttpClient::receive(SqlRequest &request)
{
	std::string serverResponse;

	do
	{
		while ( !httpSend(L"www.domain.com", L"/getrequest", L"GET", NULL, &serverResponse) )
		{
			::Sleep(ERROR_PAUSE);
		}

	} while ( !parser::text2request(serverResponse, request) );
}

// static
void HttpClient::send(const SqlResponse &response)
{
	std::string body;
	parser::response2text(response, body);

	while ( !httpSend(L"www.domain.com", L"/postresponse", L"POST", &body) )
	{
		::Sleep(ERROR_PAUSE);
	}
}

// static
void HttpClient::reset()
{
	while ( !httpSend(L"www.domain.com", L"/reset", L"GET") )
	{
		::Sleep(ERROR_PAUSE);
	}
}

// static
bool HttpClient::httpSend(LPCWSTR domain, LPCWSTR path, LPCWSTR verb, const std::string *body /* = NULL */, std::string *response /* = NULL */)
{
	bool success = false;

	HINTERNET internet = ::InternetOpen(L"SQL Proxy v0.1", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
	if (internet)
	{
		HINTERNET connection = ::InternetConnect(internet, domain, INTERNET_DEFAULT_HTTP_PORT, 0, 0, INTERNET_SERVICE_HTTP, 0, 0);
		if (connection)
		{
			HINTERNET request = ::HttpOpenRequest(connection, verb, path, 0, 0, 0, INTERNET_FLAG_PRAGMA_NOCACHE, 0);
			if (request)
			{
				BOOL result;

				if (body)
					result = ::HttpSendRequest(request, 0, 0, (LPVOID)body->c_str(), body->length());
				else
					result = ::HttpSendRequest(request, 0, 0, 0, 0);

				if (result)
				{
					char statusCodeText[100];
					DWORD length = sizeof(statusCodeText) - 1;
					DWORD index = 0;
					if ( ::HttpQueryInfo(request, HTTP_QUERY_STATUS_CODE, statusCodeText, &length, &index) )
					{
						statusCodeText[length] = '\0';
						if ( ::StrToIntA(statusCodeText) == 200 )
						{
							success = true;

							if (response)
							{
								response->clear();
								char buffer[1024*100] = {0};
								DWORD bytesRead = 0;
								while ( ::InternetReadFile(request, buffer, sizeof(buffer) - 1, &bytesRead) && bytesRead != 0 )
								{
									buffer[bytesRead] = 0;
									*response += buffer;
								}
							}
						}
					}
				}

				::InternetCloseHandle(request);
			}
			::InternetCloseHandle(connection);
		}
		::InternetCloseHandle(internet);
	}

	return success;
}
